﻿using CarArranger.Model;
using System;
using System.Windows.Forms;
using System.Linq;

namespace CarArranger.Forms
{
    public partial class EditCarList : Form
    {
        public CarList CarList { get; set; } = new CarList();
        public Yard _yard;

        public EditCarList(Yard yard)
        {
            _yard = yard;
            InitializeComponent();
            UpdateTrackSelect();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AddCarGroup form = new AddCarGroup();
            DialogResult result = form.ShowDialog();
            if (result == DialogResult.OK)
            {
                CarList.Clear();
                string[] str = form.CarStr.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                foreach (string s in str)
                {
                    if (s == string.Empty) continue;
                    string[] ss = s.Split(',');
                    CarGroup cg = new CarGroup()
                    {
                        DestNum = int.Parse(ss[0]),
                        CarNum = int.Parse(ss[1])
                    };
                    CarList.Add(cg);
                }
                UpdateList();
            }
        }

        private void UpdateList()
        {
            listView1.Items.Clear();
            foreach (CarGroup cg in CarList)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Text = cg.DestNum.ToString();
                listViewItem.Tag = cg;
                listViewItem.SubItems.Add(cg.CarNum.ToString());
                this.listView1.Items.Add(listViewItem);
            }
        }

        private void UpdateTrackSelect()
        {
            TrackSelect.Items.Clear();
            if (_yard != null)
            {
                foreach (Track track in _yard.Tracks)
                {
                    TrackSelect.Items.Add(track.Name);
                }
            }
            TrackSelect.SelectedIndex = 0;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            CarList.PrimalTrack = _yard.Tracks.FirstOrDefault(i => i.Name == TrackSelect.Text);
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void EditCarList_Shown(object sender, EventArgs e)
        {

        }

        private void button8_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
